﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;

public class User : MonoBehaviour {



    private static readonly string lastUserName = "lastUserName";
    private static readonly string lastUserNameTime = "lastUserNameTime";
    private static readonly string lastUserPsd = "lastUserPsd";
    private static int recordExpireDays = 14;

    public GameObject register = null;
    public GameObject login = null;
    public GameObject forget = null;

    public GameObject regButtonNext = null;
    public GameObject regButtonCommit = null;


    // register -----------------------------------------
    public tabpage regTablePage = null;
    public InputField regInputCDKey = null;
    public InputField regInputPhoneNumber = null;
    public InputField regInputPsd = null;
    public InputField regInputCode = null;
    public InputField regInputName = null;
    public Dropdown regDropProvince = null;
    public Dropdown regDropSchool = null;

    public Button btnReqPhoneCodeReg = null;
    // register end  -------------------------------------


    // login ------------------------------------------
    public InputField loginInputPhone = null;
    public InputField loginPsd = null;
    // login end --------------------------------------


    // forget -------------------------------------------
    public InputField forgetInputPhone = null;
    public InputField forgetInputPsd = null;
    public InputField forgetInputCode = null;

    public Button btnReqPhoneCodeForget = null;
    // forget end -----------------------------------------


    private static User instance = null;
    public static User GetInstance()
    { return instance; }

    private void Awake()
    {
        instance = this;
    }
    // Use this for initialization
    void Start () {

//        ShowReg();
        
    }
	
	// Update is called once per frame
	void Update () {
		
	}

    public void Hide()
    {
        gameObject.SetActive(false);
    }

    public void ShowReg()
    {
        gameObject.SetActive(true);

        login.SetActive(false);
        forget.SetActive(false);
        register.SetActive(true);

        regTablePage.ReInit();
        regButtonCommit.SetActive(false);
        regButtonNext.SetActive(true);

        regDropProvince.AddOptions(DataManager.schoolData.GetAllProvince());
    }

    public void ShowLogin()
    {
        gameObject.SetActive(true);

        login.SetActive(true);
        forget.SetActive(false);
        register.SetActive(false);


/*        if ( PlayerPrefs.HasKey(lastUserName) && PlayerPrefs.HasKey(lastUserNameTime) )
        {
            string untime = PlayerPrefs.GetString(lastUserNameTime);
            DateTime dt1 = Convert.ToDateTime(untime);
            TimeSpan ts = DateTime.Now.Subtract(dt1);
            if ( ts.Days <= 14 )
            {
                string un = PlayerPrefs.GetString(lastUserName);
                loginInputPhone.text = un;
            }
        }*/

        if ( !IsRecordExpire() )
        {
            string un = PlayerPrefs.GetString(lastUserName);
            loginInputPhone.text = un;
        }

        
    }

    public static bool IsRecordExpire()
    {
        if (PlayerPrefs.HasKey(lastUserName) && PlayerPrefs.HasKey(lastUserNameTime) )
        {
            string untime = PlayerPrefs.GetString(lastUserNameTime);
            DateTime dt1 = Convert.ToDateTime(untime);
            TimeSpan ts = DateTime.Now.Subtract(dt1);
            if (ts.Days <= recordExpireDays)
                return false;
        }

        return true;
    }


    public static bool CheckAutoLogin()
    {
        if (IsRecordExpire())
            return false;

        if (PlayerPrefs.HasKey(lastUserPsd) == false)
            return false;

        string username = PlayerPrefs.GetString(lastUserName);
        string userpsd = PlayerPrefs.GetString(lastUserPsd);
        if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(userpsd))
            return false;

        OnLoginDo(username, userpsd);
        return true;
    }

    public void ShowForget()
    {
        gameObject.SetActive(true);

        login.SetActive(false);
        forget.SetActive(true);
        register.SetActive(false);
    }


    public void ReqSendPhoneMsg(string number)
    {
        NetMgr.ReqPhotoMeg(number,(suc, msg)=> {
            if (!suc)
                Tips.ShowBottomTip("error", Color.red, 3f);
            else
                Tips.ShowBottomTip(msg, Color.black, 3f);
        });
    }

    RespData activationCodeData = new RespData();
    public void RegNextStep()
    {

        // first step     cd key
        int nowidx = regTablePage.GetNowIdx();
        if (nowidx == 0 )
        {
            // 判断激活码
            string key = regInputCDKey.text;
            NetMgr.ReqCDKeyValid(key, (suc, msg)=> {

                if (!suc)
                {
                    Tips.ShowBottomTip(msg, Color.red, 3f);
                    Debug.Log(msg);

                    // test
                    //                    RegNextStepDo();

                    
                    return;
                }
                else
                {
                    NetMgr.ReqOrgByActCode(key, (succ, text) => {
                        activationCodeData.Reset(text);
                        string province = null;
                        string city = null;
                        string dist = null;
                        if (activationCodeData.Get("facilitator") != null)
                        {
                            regDropProvince.ClearOptions();
                            province = activationCodeData.Get("facilitator", "province");
                            city = activationCodeData.Get("facilitator", "city");
                            dist = activationCodeData.Get("facilitator", "district");

                            List<string> litemp = new List<string>();
                            litemp.Add(province + "," + city + "," + dist);
                            regDropProvince.AddOptions(litemp);

//                            regDropSchool.ClearOptions();
//                            string facid = activationCodeData.Get("facilitator", "facilitator_id");

                        }
                        else if (activationCodeData.Get("organization") != null)
                        {
                            regDropProvince.ClearOptions();
                            province = activationCodeData.Get("organization", "province");
                            city = activationCodeData.Get("organization", "city");
                            dist = activationCodeData.Get("organization", "district");

                            province = province == null ? "" : province;
                            city = city == null ? "" : city;
                            dist = dist == null ? "" : dist;

                            List<string> litemp = new List<string>();
                            litemp.Add(province + "," + city + "," + dist);
                            regDropProvince.AddOptions(litemp);

//                            litemp.Clear();
//                            string orgid = activationCodeData.Get("organization", "id");
//                            orgid = orgid == null ? "" : orgid;
//                            litemp.Add(orgid);

                        }
                        else
                        {
                            RegNextStepDo();
                            return;
                        }

                        if (activationCodeData.Get("user") != null)
                        {
                            regDropSchool.ClearOptions();
                            string orgn = activationCodeData.Get("user", "name");
                            regDropSchool.AddOptions(new List<string>() { orgn });
                        }
                        else
                        {
                            if ( !string.IsNullOrEmpty( province ) && !string.IsNullOrEmpty(city) && !string.IsNullOrEmpty(dist) )
                            {
                                OnRegProvinceValueChanged(0);
                            }
                        }
                    });
                    RegNextStepDo();
                }
            });

            
        }
        else if ( nowidx == 1 )
        {
            // 手机验证码
            if (!string.IsNullOrEmpty(regInputPhoneNumber.text) && !string.IsNullOrEmpty(regInputCode.text) && !string.IsNullOrEmpty(regInputPsd.text))
            {

                RegNextStepDo();
            }

            else
                Tips.ShowBottomTip("信息填写不完整", Color.red, 3f);
        }
    }
    void RegNextStepDo()
    {
        int idx = regTablePage.GetNextIdx();
        regTablePage.PullTab(idx);

        if (idx == (regTablePage.GetTabCount() - 1))
        {
            regButtonCommit.SetActive(true);
            regButtonNext.SetActive(false);
        }
        else
        {
            regButtonCommit.SetActive(false);
            regButtonNext.SetActive(true);
        }
    }

    void RegRefreshButtonNextOrCommit()
    {
        int idx = regTablePage.GetNowIdx();

        if (idx == (regTablePage.GetTabCount() - 1))
        {
            regButtonCommit.SetActive(true);
            regButtonNext.SetActive(false);
        }
        else
        {
            regButtonCommit.SetActive(false);
            regButtonNext.SetActive(true);
        }
    }

    public void RegCommit()
    {
        if (regDropSchool.options.Count == 0)
            return;


        string orgid = activationCodeData.Get("organization", "id");
        if (orgid == null)
            orgid = activationCodeData.Get("facilitator", "facilitator_id");
        if ( orgid == null )
            orgid = DataManager.schoolsData.GetIDByName(regDropSchool.options[regDropSchool.value].text);

        string cdkey = regInputCDKey.text;
        string psd = regInputPsd.text;
        string code = regInputCode.text;
        string name = regInputName.text;
        string account = regInputPhoneNumber.text;

     
        
//        string orgid = DataManager.schoolsData.GetIDByName (regDropSchool.options[regDropSchool.value].text);
        Debug.Log(orgid);
        NetMgr.ReqRegister(cdkey, name, account, psd, orgid, code, (suc, msg) => {
            if (!suc)
                Tips.ShowBottomTip(msg, Color.red, 3f);
            else
            {
                Tips.ShowBottomTip("恭喜您，注册成功！", Color.black, 3f);
                Hide();
            }
                
        });
    }

    public void RegLastStep()
    {
        int idx = regTablePage.GetNowIdx();
        if (idx == 0)
            Hide();
        else
            regTablePage.PullTab(idx - 1);

        RegRefreshButtonNextOrCommit();

    }

    public void RegReqPhoneCode()
    {
        string number = regInputPhoneNumber.text;



        NetMgr.ReqPhotoMeg(number, (suc, msg) => {
            if (!suc)
            {
                Tips.ShowBottomTip(msg, Color.red, 3f);
            }
            else
            {
                Tips.ShowBottomTip("验证码已发送", Color.black, 3f);

                PhoneCodeCD(btnReqPhoneCodeReg, btnReqPhoneCodeReg.GetComponentInChildren<Text>(), "手机验证码", 60, "reg");
            }
        });
    }

    public void ForgetReqPhoneCode()
    {
        string number = forgetInputPhone.text;



        NetMgr.ReqPhotoMeg(number, (suc, msg) => {
            if (!suc)
            {
                Tips.ShowBottomTip(msg, Color.red, 3f);
            }
            else
            {
                Tips.ShowBottomTip("验证码已发送", Color.black, 3f);

                PhoneCodeCD(btnReqPhoneCodeForget, btnReqPhoneCodeForget.GetComponentInChildren<Text>(), "手机验证码", 60, "forget");
            }
        });
    }

    public void OnRegProvinceValueChanged(int idx)
    {
        string v = regDropProvince.options[idx].text;
        string[] s = v.Split(',');

        NetMgr.ReqSchool(s[0], s[1], s[2], (suc, sd) => {

            if ( suc)
            {
                List<string> l = sd.GetAllOrgnazationName();
                regDropSchool.ClearOptions();
                regDropSchool.AddOptions(l);
            }
            else
            {
                Tips.ShowBottomTip("error", Color.red, 3f);
            }


        });


    }


    bool test = true;
    public void OnLogin()
    {

        // testing login success
 /*               DataManager.appUserData.id = "1";
                DataManager.appUserData.name = "2";
                DataManager.appUserData.type = "teacher";
                lessonUI.GetInstance().ShowLessonList();
                Hide();
                Index.Hide();
                return;
                */

        if ( test )
        {
            DataManager.appUserData.id = "1";
            DataManager.appUserData.type = "teacher";
            // 进入主界面
            lessonUI.GetInstance().ShowLessonList();
            Hide();
            Index.Hide();

            return;
        }

        string phone = loginInputPhone.text;
        string psd = loginPsd.text;

        OnLoginDo(phone, psd);
        
    }

    public static void OnLoginDo( string uname, string psd )
    {
        string phone = uname;
        string pasd = psd;

        NetMgr.ReqLogin(phone, pasd, (suc, msg) => {
            if (suc)
            {

                Tips.ShowBottomTip("登录成功", Color.black, 3f);
                DataManager.appUserData.Reset(msg);

                PlayerPrefs.SetString(lastUserName, phone);
                PlayerPrefs.SetString(lastUserNameTime, DateTime.Now.ToString());
                PlayerPrefs.SetString(lastUserPsd, pasd);

                // 进入主界面
                lessonUI.GetInstance().ShowLessonList();
                instance.Hide();
                Index.Hide();


            }

            else
                Tips.ShowBottomTip(msg, Color.red, 3f);
        });
    }

    public void OnLoginBack()
    {
        Hide();
    }

    public void OnForget()
    {
        ShowForget();
    }


    public void OnForgetBack()
    {
        ShowLogin();
    }

    public void OnBtnCommitForget()
    {
        string account = forgetInputPhone.text;
        string psd = forgetInputPsd.text;
        string code = forgetInputCode.text;

        NetMgr.ReqForget(account, psd, code, (suc, msg) => {
            if ( suc )
            {
                Tips.ShowBottomTip("重置密码成功", Color.black, 3f);
                ShowLogin();
            }
            else
                Tips.ShowBottomTip(msg, Color.red, 3f);
        });
    }



    public class ArgPhotoCodeCD
    {

        public string name = null;
        public Button btn = null;
        public Text t = null;
        public string txtOrg = null;
    }
    protected Dictionary<string, ArgPhotoCodeCD> dictArgPhotoCodeCD = new Dictionary<string, ArgPhotoCodeCD>();

    public void PhoneCodeCD(Button btn, Text t, string txtOrg, int timeElapse, string name= "name1")
    {
        btn.interactable = false;

        Timer_yang timer = Timer_yang.createTimer(false, name, timeElapse);
        timer.tickEvent = new Timer_yang.Tick(TickEvent);
        timer.thenEvent = new Timer_yang.Tick(ThenEvent);

        ArgPhotoCodeCD arg = new ArgPhotoCodeCD();
        arg.name = name;
        arg.btn = btn;
        arg.t = t;
        arg.txtOrg = txtOrg;
        dictArgPhotoCodeCD.Add(name, arg);

        timer.start();

    }

    public void TickEvent(GameObject obj, Timer_yang.timerEventArgs args)
    {
        if ( dictArgPhotoCodeCD.ContainsKey( obj.name ))
        {
            ArgPhotoCodeCD arg = dictArgPhotoCodeCD[obj.name];

            Timer_yang timer = obj.GetComponent<Timer_yang>();
            arg.t.text = Convert.ToInt32(timer.RestTime).ToString();
        }
    }

    public void ThenEvent(GameObject obj, Timer_yang.timerEventArgs args)
    {
        if (dictArgPhotoCodeCD.ContainsKey(obj.name))
        {
            ArgPhotoCodeCD arg = dictArgPhotoCodeCD[obj.name];

            arg.btn.interactable = true;
            arg.t.text = arg.txtOrg;

            dictArgPhotoCodeCD.Remove(obj.name);
        }
    }

}
